package org.grottarossa.ui.core.casemanagement.discussions;




import java.math.BigDecimal;
import java.util.HashMap;
import java.util.ResourceBundle;

import org.grottarossa.template.data.Tree;
import org.grottarossa.template.data.pojo.discussions.Discussion;
import org.grottarossa.template.drivers.DriverException;
import org.grottarossa.template.drivers.components.tokens.CaseManagementId;
import org.grottarossa.template.drivers.components.tokens.DiscussionManagementId;
import org.grottarossa.ui.core.ApplicationSession;
import org.grottarossa.ui.core.BPMResource;
import org.grottarossa.ui.core.base.BasePanel;
import org.grottarossa.ui.core.container.DiscussionContainer;
import org.grottarossa.ui.core.i18n.DM;

import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import com.vaadin.event.Action;
import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Form;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TreeTable;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Window.Notification;

public class DiscussionListPanel extends BasePanel
{
	private static final long serialVersionUID = 5367036209492343058L;
	HashMap<String, Tree<Discussion>> discussionTrees = null;
	Discussion discussion;
	private Button newDiscussion = null;
	private Button save = null;

	final Action EDIT;
	final Action DELETE;
	final Action REPLY;
	final Action[] ACTIONS;
	CaseManagementId caseId = null;
	private TreeTable m_treeTable=null;

	private void reload(CaseManagementId caseId)
	{
		HashMap<String, Tree<Discussion>> discussionTreesToReload = null;

		try
		{
			discussionTreesToReload = m_appSession.getBuilder().getDiscussionManagement().getDiscussionList( caseId );
		}
		catch (DriverException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		DiscussionContainer container = new DiscussionContainer(discussionTreesToReload);
		m_treeTable.setContainerDataSource(container);
		m_treeTable.setVisibleColumns(container.getVisibleColumns());

		for (Object obj : container.getItemIds() )
		{
			Item item = container.getItem(obj);
			DiscussionManagementId dId = (DiscussionManagementId)item.getItemProperty("id").getValue();
			try
			{
				if ( m_appSession.getBuilder().getDiscussionManagement().getDiscussionElement(caseId , dId ).getReplies() == 0  )
				{
					m_treeTable.setItemIcon(obj, BPMResource.ICON_DISCUSSION);
				}
				else
				{
					m_treeTable.setItemIcon(obj, BPMResource.ICON_DISCUSSION_WITH_REPLY);
				}
			}
			catch (Exception e)
			{
				// TODO: handle exception
			}
			m_treeTable.setCollapsed(obj, false);
		}
	}

	public DiscussionListPanel(ApplicationSession appSession, CaseManagementId id)
	{
		super(appSession, DM.instance().getBundle(DiscussionListPanel.class.getName()));

		caseId = id;

		EDIT = new Action(m_localizer.getString("discussion.action.edit"));
		DELETE = new Action(m_localizer.getString("discussion.action.delete"));
		REPLY = new Action(m_localizer.getString("discussion.action.reply"));
		ACTIONS = new Action[] {EDIT, REPLY, DELETE};

		initializeComponents();
	}

	@Override
	protected void initializeComponents()
	{
		VerticalLayout v = new VerticalLayout();
		v.setHeight(100, Sizeable.UNITS_PERCENTAGE);
		v.setWidth(100, Sizeable.UNITS_PERCENTAGE);
		setLayout(v);

		discussion = new Discussion();

		try
		{
			discussionTrees = m_appSession.getBuilder().getDiscussionManagement().getDiscussionList(caseId );
		}
		catch (DriverException e)
		{
			e.printStackTrace();
		}

		DiscussionContainer discussionContainer = new DiscussionContainer(discussionTrees);

		m_treeTable = new TreeTable();
		m_treeTable.setContainerDataSource(discussionContainer);
		m_treeTable.setHeight(100, Sizeable.UNITS_PERCENTAGE);
		m_treeTable.setWidth(100, Sizeable.UNITS_PERCENTAGE);
		m_treeTable.setColumnCollapsingAllowed(true);
		m_treeTable.setSortDisabled(true);
		m_treeTable.setVisibleColumns(discussionContainer.getVisibleColumns());

		for (Object obj : discussionContainer.getItemIds() )
		{
			Item item = discussionContainer.getItem(obj);
			DiscussionManagementId dId = (DiscussionManagementId)item.getItemProperty("id").getValue();

			try
			{
				if ( m_appSession.getBuilder().getDiscussionManagement().getDiscussionElement(caseId , dId ).getReplies() == 0  )
				{
					m_treeTable.setItemIcon(obj, BPMResource.ICON_DISCUSSION);
				}
				else
				{
					m_treeTable.setItemIcon(obj, BPMResource.ICON_DISCUSSION_WITH_REPLY);
				}
			}
			catch (Exception e)
			{
				// TODO: handle exception
			}
		}

		m_treeTable.addActionHandler(new Action.Handler()
		{
			public Action[] getActions(Object target, Object sender) {
				return ACTIONS;
			}
			public void handleAction(Action action, Object sender, Object target)
			{
				if(EDIT.equals(action))
				{
					updateDiscussion(caseId,(DiscussionManagementId)m_treeTable.getItem(target).getItemProperty("id").getValue());
					m_treeTable.requestRepaint();
				}
				else if(REPLY.equals(action))
				{
					replyDiscussion(caseId,(DiscussionManagementId)m_treeTable.getItem(target).getItemProperty("id").getValue());
					m_treeTable.requestRepaint();
				}
				else if(DELETE.equals(action))
				{
					deleteDiscussion(caseId,(DiscussionManagementId)m_treeTable.getItem(target).getItemProperty("id").getValue());
				}
			}
		});
		newDiscussion = new Button(m_localizer.getString("discussion.button.new"), new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				newDiscussion(caseId);
				m_treeTable.requestRepaint();
				getContent().requestRepaint();
			}
		});

		v.addComponent(m_treeTable);
		v.addComponent(newDiscussion);
		v.setExpandRatio(m_treeTable, 1000);
		v.setExpandRatio(newDiscussion, 1);
	}

	public void newDiscussion(final CaseManagementId caseId)
	{
		final Window newDiscussion = new Window(m_localizer.getString("discussion.window.new"));
		GridLayout gl = new GridLayout(1,2);
		gl.setMargin(true);
		gl.setSpacing(true);
		newDiscussion.setContent(gl);
		final BeanItem<Discussion> discussionItem = new BeanItem<Discussion>(discussion);
		final Form topicForm = new DiscussionForm(caseId, discussionItem, 0);
		gl.addComponent(topicForm, 0, 0);
		gl.setComponentAlignment(topicForm, Alignment.MIDDLE_CENTER);

		save = new Button(m_localizer.getString("discussion.button.save"), new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {

				Discussion newDiscussionElem = (Discussion) discussionItem.getBean();
				newDiscussionElem.setCaseId( caseId );

				try
				{
					m_appSession.getBuilder().getDiscussionManagement().createDiscussionItem(newDiscussionElem);
				}
				catch (DriverException e)
				{
					showError(e);
				}

				((Window)newDiscussion.getParent()).removeWindow(newDiscussion);
				reload(caseId);
			}
		});

		gl.addComponent(save, 0, 1);
		gl.setComponentAlignment(save, Alignment.MIDDLE_RIGHT);
		newDiscussion.setModal(true);
		newDiscussion.setSizeUndefined();

		getWindow().addWindow(newDiscussion);
	}

	public void replyDiscussion(final CaseManagementId caseId,final DiscussionManagementId id)
	{
		final Window replyDiscussion = new Window(m_localizer.getString("discussion.window.reply"));
		GridLayout gl = new GridLayout(1,2);
		gl.setMargin(true);
		gl.setSpacing(true);
		replyDiscussion.setContent(gl);

		try
		{
			discussion.setName(m_appSession.getBuilder().getDiscussionManagement().getDiscussionName( caseId ,id ));
		}
		catch (DriverException e1)
		{
			showError(e1);
		}

		discussion.setBody("");
		final BeanItem discussionItem = new BeanItem(discussion);
		final Form topicForm = new DiscussionForm(caseId, discussionItem, 1);
		gl.addComponent(topicForm, 0, 0);
		gl.setComponentAlignment(topicForm, Alignment.MIDDLE_CENTER);
		save = new Button(m_localizer.getString("discussion.button.save"), new Button.ClickListener() {
					public void buttonClick(ClickEvent event) {
						try
						{
							m_appSession.getBuilder().getDiscussionManagement().replyDiscussionItem(caseId ,id, (Discussion)discussionItem.getBean());
						}
						catch (DriverException e)
						{
							showError(e);
						}

						((Window)replyDiscussion.getParent()).removeWindow(replyDiscussion);
						reload(caseId);
					}
				});
		gl.addComponent(save, 0, 1);
		gl.setComponentAlignment(save, Alignment.MIDDLE_RIGHT);
		replyDiscussion.setModal(true);
		replyDiscussion.setSizeUndefined();

		getWindow().addWindow(replyDiscussion);
	}

	public void updateDiscussion(final CaseManagementId caseId, DiscussionManagementId id) {
			final Window editDiscussion = new Window(m_localizer.getString("discussion.window.update"));
			GridLayout gl = new GridLayout(1,2);
			gl.setMargin(true);
			gl.setSpacing(true);
			editDiscussion.setContent(gl);
			Discussion discussion = null;

			try
			{
				discussion = m_appSession.getBuilder().getDiscussionManagement().getDiscussionElement(caseId ,id );
			}
			catch (DriverException e1)
			{
				showError(e1);
			}

			final BeanItem discussionItem = new BeanItem(discussion);
			int par = 0;
			//se messaggio figlio, non si pu� cambiare il suo nome
			if(discussion.getParentId() != null) {
				par = 2;
			}
			else {
				par = 3;
			}
			final DiscussionForm topicForm = new DiscussionForm(null, discussionItem, par);
			gl.addComponent(topicForm, 0, 0);
			gl.setComponentAlignment(topicForm, Alignment.MIDDLE_CENTER);
			save = new Button(m_localizer.getString("discussion.button.save"), new Button.ClickListener() {
				public void buttonClick(ClickEvent event) {
					topicForm.commit();

					Discussion discussionToUpdate = (Discussion)discussionItem.getBean();
					discussionToUpdate.setCaseId(new CaseManagementId(caseId));

					try
					{
						m_appSession.getBuilder().getDiscussionManagement().updateDiscussionItem(discussionToUpdate);
					}
					catch (DriverException e)
					{
						showError(e);
					}

					((Window)editDiscussion.getParent()).removeWindow(editDiscussion);
					reload(caseId);
				}
			});
			gl.addComponent(save, 0, 1);
			gl.setComponentAlignment(save, Alignment.MIDDLE_RIGHT);
			editDiscussion.setModal(true);
			editDiscussion.setSizeUndefined();

			getWindow().addWindow(editDiscussion);
	}

	public void deleteDiscussion(final CaseManagementId caseId,DiscussionManagementId id)
	{
		final Window deleteDiscussion = new Window(m_localizer.getString("discussion.window.delete"));
		GridLayout gl = new GridLayout(2,2);
		gl.setMargin(true);
		gl.setSpacing(true);
		deleteDiscussion.setSizeUndefined();
		deleteDiscussion.setContent(gl);
		deleteDiscussion.setModal(true);
		Discussion discussion = null;

		try
		{
			discussion = m_appSession.getBuilder().getDiscussionManagement().getDiscussionElement( caseId,id);
		}
		catch (DriverException e)
		{
			showError(e);
		}

		Label label = new Label(m_localizer.getString("discussion.label.delete"));

		final Discussion fDiscussion = discussion;
		Button ok = new Button("Ok", new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				if(fDiscussion.getReplies() > 0) {
					getWindow().showNotification(m_localizer.getString("discussion.notification.delete"), Notification.TYPE_ERROR_MESSAGE);
				}
				else {
					try
					{
						m_appSession.getBuilder().getDiscussionManagement().deleteDiscussionItem(  caseId ,fDiscussion.getId() );
					}
					catch (DriverException e)
					{
						showError(e);
					}

					((Window)deleteDiscussion.getParent()).removeWindow(deleteDiscussion);
					reload(caseId);
				}
			}
		});
		Button cancel = new Button(m_localizer.getString("discussion.button.cancel"), new Button.ClickListener() {
			public void buttonClick(ClickEvent event) {
				((Window)deleteDiscussion.getParent()).removeWindow(deleteDiscussion);
				reload(caseId);
			}
		});
		gl.addComponent(label, 0, 0, 1, 0);
		gl.setComponentAlignment(label, Alignment.MIDDLE_CENTER);
		gl.addComponent(ok, 0, 1);
		gl.setComponentAlignment(ok, Alignment.MIDDLE_CENTER);
		gl.addComponent(cancel, 1, 1);
		gl.setComponentAlignment(cancel, Alignment.MIDDLE_CENTER);

		getWindow().addWindow(deleteDiscussion);
	}
}